<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 * 记录类型管理
 *
 * @icon fa fa-circle-o
 */
class Dnstype extends Backend
{
    
    /**
     * Dnstype模型对象
     * @var \app\admin\model\Dnstype
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Dnstype;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $lists = $list->items();

            $result = array("total" => $list->total(), "rows" => $lists);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;

                //解析查重
                $dnslist = Db::name('dns_type')
                    ->where('system_name', '=', $params['system_name'])
                    ->find();
                if($dnslist){
                    $return['msg'] = '批量解析DNS已存在';
                    return $return;
                }
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->handle_dnschannel($params);
                    if($result == false){
                        $this->error('请填写DNS模版规则');
                    }
                    $data['porkbun'] = $params['porkbun'];
                    $data['godaddy'] = $params['godaddy'];
                    $data['namesilo'] = $params['namesilo'];
                    $data['namecheap'] = $params['namecheap'];
                    unset($params['porkbun']);
                    unset($params['godaddy']);
                    unset($params['namesilo']);
                    unset($params['namecheap']);
                    $params['createtime'] = time();
                    $params['updatetime'] = time();
                    $result = $this->model->allowField(true)->insertGetId($params);
                    $data['id'] = $result;
                    $result = $this->add_dnschannel($data,1);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;

                //解析查重
                $dnslist = Db::name('dns_type')
                    ->where('system_name', '=', $params['system_name'])
                    ->find();
                if($dnslist){
                    if($dnslist['id'] !== (int)$ids){
                        $return['msg'] = '批量解析DNS已存在';
                        return $return;
                    }
                }
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    $result = $this->handle_dnschannel($params);
                    if($result == false){
                        $this->error('请填写DNS模版规则');
                    }
                    $data['porkbun'] = $params['porkbun'];
                    $data['godaddy'] = $params['godaddy'];
                    $data['namesilo'] = $params['namesilo'];
                    $data['namecheap'] = $params['namecheap'];
                    unset($params['porkbun']);
                    unset($params['godaddy']);
                    unset($params['namesilo']);
                    unset($params['namecheap']);
                    $params['createtime'] = time();
                    $params['updatetime'] = time();
                    $result = $row->allowField(true)->save($params);
                    $data['id'] = $ids;
                    $result = $this->add_dnschannel($data,2);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        //查询DNS模版规则
        $typechannel = Db::name('dns_typechannel')
            ->where('type_id', '=', $row['id'])
            ->select();
        $porkbun = array();
        $godaddy = array();
        $namesilo = array();
        $namecheap = array();
        foreach ($typechannel as $k=>$v){
            $channel = Db::name('dns_channel')
                ->where('id', '=', $v['channel_id'])
                ->find();
            if(!empty($channel)){
                if($channel['apitype'] == 1){
                    $data['name'] = $channel['name'];
                    $data['type'] = $channel['type'];
                    $data['info'] = $channel['info'];
                    $data['ttl'] = (string)$channel['ttl'];
                    $porkbun[] = $data;
                }
                if($channel['apitype'] == 2){
                    $data2['name'] = $channel['name'];
                    $data2['type'] = $channel['type'];
                    $data2['ip'] = $channel['ip'];
                    $data2['ttl'] = (string)$channel['ttl'];
                    $godaddy[] = $data2;
                }
                if($channel['apitype'] == 3){
                    $data['name'] = $channel['name'];
                    $data['type'] = $channel['type'];
                    $data['info'] = $channel['info'];
                    $data['ttl'] = (string)$channel['ttl'];
                    $namesilo[] = $data;
                }
                if($channel['apitype'] == 4){
                    $data['name'] = $channel['name'];
                    $data['type'] = $channel['type'];
                    $data['info'] = $channel['info'];
                    $data['ttl'] = (string)$channel['ttl'];
                    $namecheap[] = $data;
                }
            }
        }
        if(empty($porkbun)){
            $porkbun = '';
        }else{
            $porkbun = json_encode($porkbun);
        }
        if(empty($godaddy)){
            $godaddy = '';
        }else{
            $godaddy = json_encode($godaddy);
        }
        if(empty($namesilo)){
            $namesilo = '';
        }else{
            $namesilo = json_encode($namesilo);
        }
        if(empty($namecheap)){
            $namecheap = '';
        }else{
            $namecheap = json_encode($namecheap);
        }

        $this->view->assign("porkbun", $porkbun);
        $this->view->assign("godaddy", $godaddy);
        $this->view->assign("namesilo", $namesilo);
        $this->view->assign("namecheap", $namecheap);
        return $this->view->fetch();
    }

    /**
     * @return handle_dnschannel
     */
    public function handle_dnschannel($params)
    {
        $porkbun = json_decode($params['porkbun'],true);
        $godaddy = json_decode($params['godaddy'],true);
        $namesilo = json_decode($params['namesilo'],true);
        $namecheap = json_decode($params['namecheap'],true);
        $error = 0;
        if(empty($porkbun)){
            $error = $error + 1;
        }else{
            if(isset($porkbun[0]['id']) && $porkbun[0]['id'] == 1){
                $error = $error + 1;
            }
        }
        if(empty($godaddy)){
            $error = $error + 1;
        }else{
            if(isset($godaddy[0]['id']) && $godaddy[0]['id'] == 1){
                $error = $error + 1;
            }
        }
        if(empty($namesilo)){
            $error = $error + 1;
        }else{
            if(isset($namesilo[0]['id']) && $namesilo[0]['id'] == 1){
                $error = $error + 1;
            }
        }
        if(empty($namecheap)){
            $error = $error + 1;
        }else{
            if(isset($namecheap[0]['id']) && $namecheap[0]['id'] == 1){
                $error = $error + 1;
            }
        }
        if($error == 4){
            return false;
        }
        return true;
    }

    /**
     * @return handle_dnschannel
     */
    public function add_dnschannel($params,$type)
    {
        $porkbun = json_decode($params['porkbun'],true);
        $godaddy = json_decode($params['godaddy'],true);
        $namesilo = json_decode($params['namesilo'],true);
        $namecheap = json_decode($params['namecheap'],true);
        if($type == 2){
            $this->del_dnschannel($params['id']);
        }
        $porkbun = $this->handle_porkbun($porkbun,$params['id']);
        $godaddy = $this->handle_godaddy($godaddy,$params['id']);
        $namesilo = $this->handle_namesilo($namesilo,$params['id']);
        $namecheap = $this->handle_namecheap($namecheap,$params['id']);
        return true;
    }

    /**
     * @return del_dnschannel
     */
    public function del_dnschannel($id)
    {
        $typechannel = Db::name('dns_typechannel')
            ->where('type_id', '=', $id)
            ->select();
        foreach ($typechannel as $k=>$v){
            Db::name('dns_channel')->where('id', '=', $v['channel_id'])->delete();
        }
        $return = Db::name('dns_typechannel')->where('type_id', '=', $id)->delete();
        return $return;
    }

    /**
     * @return handle_porkbun
     */
    public function handle_porkbun($porkbun,$id)
    {
        $return = false;
        if(!empty($porkbun)){
            foreach ($porkbun as $k=>$v){
                $datatype['apitype'] = 1;
                $datatype['name'] = $v['name'];
                $datatype['type'] = $v['type'];
                $datatype['ttl'] = $v['ttl'];
                $datatype['info'] = $v['info'];
                $datatype['createtime'] = time();
                $datatype['updatetime'] = time();
                $channel_id = Db::name('dns_channel')->insertGetId($datatype);
                $typechannel['createtime'] = time();
                $typechannel['updatetime'] = time();
                $typechannel['type_id'] = $id;
                $typechannel['channel_id'] = $channel_id;
                $return = Db::name('dns_typechannel')->insert($typechannel);
            }
        }
        return $return;
    }

    /**
     * @return handle_porkbun
     */
    public function handle_namesilo($namesilo,$id)
    {
        $return = false;
        if(!empty($namesilo)){
            foreach ($namesilo as $k=>$v){
                $datatype['apitype'] = 3;
                $datatype['name'] = $v['name'];
                $datatype['type'] = $v['type'];
                $datatype['ttl'] = $v['ttl'];
                $datatype['info'] = $v['info'];
                $datatype['createtime'] = time();
                $datatype['updatetime'] = time();
                $channel_id = Db::name('dns_channel')->insertGetId($datatype);
                $typechannel['createtime'] = time();
                $typechannel['updatetime'] = time();
                $typechannel['type_id'] = $id;
                $typechannel['channel_id'] = $channel_id;
                $return = Db::name('dns_typechannel')->insert($typechannel);
            }
        }
        return $return;
    }

    /**
     * @return handle_porkbun
     */
    public function handle_namecheap($namecheap,$id)
    {
        $return = false;
        if(!empty($namecheap)){
            foreach ($namecheap as $k=>$v){
                $datatype['apitype'] = 4;
                $datatype['name'] = $v['name'];
                $datatype['type'] = $v['type'];
                $datatype['ttl'] = $v['ttl'];
                $datatype['info'] = $v['info'];
                $datatype['createtime'] = time();
                $datatype['updatetime'] = time();
                $channel_id = Db::name('dns_channel')->insertGetId($datatype);
                $typechannel['createtime'] = time();
                $typechannel['updatetime'] = time();
                $typechannel['type_id'] = $id;
                $typechannel['channel_id'] = $channel_id;
                $return = Db::name('dns_typechannel')->insert($typechannel);
            }
        }
        return $return;
    }

    /**
    * @return handle_godaddy
     */
    public function handle_godaddy($godaddy,$id)
    {
        $return = false;
        if(!empty($godaddy)){
            foreach ($godaddy as $k=>$v){
                $datatype['apitype'] = 2;
                $datatype['name'] = $v['name'];
                $datatype['type'] = $v['type'];
                $datatype['ttl'] = $v['ttl'];
                $datatype['ip'] = $v['ip'];
                $datatype['createtime'] = time();
                $datatype['updatetime'] = time();
                $channel_id = Db::name('dns_channel')->insertGetId($datatype);
                $typechannel['createtime'] = time();
                $typechannel['updatetime'] = time();
                $typechannel['type_id'] = $id;
                $typechannel['channel_id'] = $channel_id;
                $return = Db::name('dns_typechannel')->insert($typechannel);
            }
        }
        return $return;
    }
}
